<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { orgTypeData } from './index'
import { cloneDeep } from 'lodash-es'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const formSchema = reactive<FormSchema[]>([
  {
    field: 'parent.name',
    label: '父级机构',
    component: 'Input',
    componentProps: {
      disabled: true,
      placeholder: '无父级机构'
    }
  },
  {
    field: 'name',
    label: '机构名称',
    component: 'Input'
  },
  {
    field: 'orgType',
    label: '机构类型',
    component: 'Select',
    componentProps: {
      options: orgTypeData
    }
  },
  {
    field: 'shortname',
    label: '机构简称',
    component: 'Input'
  },
  {
    field: 'legal',
    label: '机构法人',
    component: 'Input'
  },
  {
    field: 'telephone',
    label: '法人联系方式',
    component: 'Input'
  },
  {
    field: 'sortOrder',
    label: '显示排序',
    value: 1,
    component: 'InputNumber',
    componentProps: {
      min: 0
    }
  }
])

const rules = reactive({
  name: [required()],
  orgType: [required()],
  shortname: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

watch(
  () => props.currentRow,
  (value) => {
    if (!value) return
    const currentRow = cloneDeep(value)
    console.log('当前表格行数据', currentRow)

    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({ submit })
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
